/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.workhorse.persistence.jpa;

import org.workhorse.persistence.BasePersistenceManager;

import javax.persistence.EntityManager;
import javax.transaction.*;

import org.workhorse.SystemException;
import org.workhorse.Identifiable;
import com.google.inject.Inject;

/**
 *  A {@link org.workhorse.persistence.PersistenceManager WorkManager} for distributed
 *  transactions using the JTA API.
 */
public class JtaPersistenceManager extends BasePersistenceManager
{
    private EntityManager entityManager;
    private UserTransaction userTransaction;

    /**
     * 
     * @param entityManager The JPA {@code EntityManager}
     * @param userTransaction The JTA {@code UserTransaction}
     */
    @Inject
    public JtaPersistenceManager(EntityManager entityManager, UserTransaction userTransaction)  {
        this.entityManager = entityManager;
        this.userTransaction = userTransaction;
    }

    /**
     * Begins the work, with the {@code EntityManager} joining the {@code UserTransaction}.
     */
    public void begin() {
        try {
            userTransaction.begin();
            entityManager.joinTransaction();
        } catch (Exception e) {
            throw new SystemException("Error starting transaction", e);
        }

    }

    public void save() {
        try {
            userTransaction.commit();
        } catch (Exception e) {
            throw new SystemException("Error starting transaction", e);
        }
    }

    public void undo() {
        try {
            userTransaction.rollback();
        } catch (Exception e) {
            throw new SystemException("Error rolling back transaction", e);
        }
    }

    public void persist(Identifiable object) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void remove(Object object) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void close() {
        entityManager.close();
    }
}
